import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

import { getSongDetail, getSongsLyric } from '../service/player';
import { formatLyric } from '@/utils/format';
import { RootState } from '@/store';
import { changeConfirmLocale } from 'antd/es/modal/locale';

interface IState {
  currentSong: any;
  lyric: ILyric[];
  lyricIndex: number;
  SongList: any[];
  ListIndex: number;
  playMode: number;
}
const initialState: IState = {
  currentSong: {},
  lyric: [],
  lyricIndex: 0,
  SongList: [],
  ListIndex: -1,
  playMode: 0,
};
// 通过 id 设置目前的歌曲 ，并添加到歌曲列表
export const fetchSongDetail = createAsyncThunk('player/songDetail', async (ids: number, { dispatch, getState }) => {
  const nowList = (getState() as RootState).player.SongList.slice();
  const findIndex = nowList.findIndex((item) => item.id === ids);
  let response: any = null;
  // 如果 不在列表中
  if (findIndex === -1) {
    let res: any = await getSongDetail(ids);
    response = res.songs[0];
    // console.log(response);
    nowList.push(response);
    // 更新 歌词 ， 列表 ， 下标
    dispatch(fetchSongLyric(ids));
    dispatch(setListIndex(nowList.length - 1));
    dispatch(setSongList(nowList));
  } else {
    // 在列表中
    response = nowList[findIndex];
    dispatch(setListIndex(findIndex));
  }
  return response;
});
// 通过 id 获取歌词
export const fetchSongLyric = createAsyncThunk('plater/lyric', async (id: number) => {
  const response: any = await getSongsLyric(id);
  return formatLyric(response.lrc.lyric);
});

// 切换歌曲 （上/下一首）
export const changeCurrentSong = (isNext: boolean) => {
  return (dispatch: any, getState: () => RootState) => {
    const { SongList, ListIndex, playMode } = getState().player;
    let nextIndex = ListIndex;
    if (playMode === 1) {
      // 随机播放模式
      nextIndex = Math.floor(Math.random() * SongList.length);
    } else {
      // 顺序播放或单曲循环
      nextIndex = nextIndex + (isNext ? 1 : -1);
      if (nextIndex > SongList.length - 1) nextIndex = 0;
      else if (nextIndex < 0) nextIndex = SongList.length - 1;
    }
    // 更新列表索引
    dispatch(setListIndex(nextIndex));
    // 如果需要更新当前歌曲
    const currentSongId = SongList[nextIndex]?.id;
    if (currentSongId) {
      dispatch(setCurrentSong(SongList[nextIndex]));
      dispatch(fetchSongLyric(currentSongId));
    }
  };
};
const PlayerSlice = createSlice({
  name: 'player',
  initialState,
  reducers: {
    setCurrentSong: (state, { payload }: PayloadAction<any>) => {
      state.currentSong = payload;
    },
    setLyric: (state, { payload }: PayloadAction<number>) => {
      state.lyricIndex = payload;
    },
    setSongList: (state, { payload }: PayloadAction<any[]>) => {
      state.SongList = payload;
    },
    setListIndex: (state, { payload }: PayloadAction<number>) => {
      state.ListIndex = payload;
    },
    setPlayMode: (state, { payload }: PayloadAction<number>) => {
      state.playMode = payload;
    },
  },
  extraReducers(builder) {
    // SongDetail
    // 处理请求开始状态
    builder.addCase(fetchSongDetail.pending, (state) => {
      console.log('pending');
    });
    // 处理请求成功状态
    builder.addCase(fetchSongDetail.fulfilled, (state, action) => {
      state.currentSong = action.payload;
    });
    // 处理请求失败状态
    builder.addCase(fetchSongDetail.rejected, (state, action) => {
      console.log('rejected');
    });

    // Songlyric
    // 处理请求开始状态
    builder.addCase(fetchSongLyric.pending, (state) => {
      // console.log('pending');
    });
    // 处理请求成功状态
    builder.addCase(fetchSongLyric.fulfilled, (state, action) => {
      state.lyric = action.payload;
    });
    // 处理请求失败状态
    builder.addCase(fetchSongLyric.rejected, (state, action) => {
      // console.log('rejected');
    });
  },
});

export const { setCurrentSong, setLyric, setListIndex, setSongList, setPlayMode } = PlayerSlice.actions;
export default PlayerSlice.reducer;
